package com.star.jersey.mybatisplus.base.web.core;

import com.star.jersey.mybatisplus.base.utils.JsonUtils;
import com.star.jersey.mybatisplus.base.utils.SpringContext;
import com.star.jersey.mybatisplus.base.web.exception.BaseExceptionAdvice;
import com.star.jersey.mybatisplus.base.web.utils.LocalDateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;

/**
 * web mvc 类
 * @author zhouhengzhe
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private static final Logger log = LoggerFactory.getLogger(WebMvcConfig.class);

    public WebMvcConfig() {
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
        registry.addFormatter(new LocalDateTimeFormatter());
    }

    @Bean
    @ConditionalOnMissingBean
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        log.info("### base init : MappingJackson2HttpMessageConverter ###");
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setDefaultCharset(Charset.defaultCharset());
        converter.setObjectMapper(JsonUtils.getMvcObjectMapper());
        return converter;
    }

    @Bean
    @ConditionalOnMissingBean
    public SpringContext springContext() {
        return new SpringContext();
    }

    @Bean({"exceptionAdvice"})
    @ConditionalOnMissingBean
    public BaseExceptionAdvice exceptionAdvice() {
        return new BaseExceptionAdvice();
    }
}
